﻿using System;
using Microsoft.AspNetCore.Mvc;

namespace FlashPay.Admin.Controllers
{
    using FlashPay.Entity;
    using FlashPay.Service.Sys;
    using FlashPay.Entity.Response.Sys;
    using System;
    using FlashPay.Entity.Request.Sys;
    using FlashPay.Entity.Parameter;
    using System.Linq;
    using FlashPay.Util;
    using FlashPay.Entity.Response.User;
    using FlashPay.Service.Company;
    using FlashPay.Service.Bank;
    using FlashPay.Service.Interface;
    using System.Collections.Generic;
    using static FlashPay.Entity.PermissionHelper;
    using FlashPay.Entity.Request.PaymentInterface;
    using Microsoft.AspNetCore.Http;

    /// <summary>
    /// 参数管理
    /// </summary>
    public class SysConfigController : BaseController
    {
        #region 注入
        /// <summary>
        /// 系统参数配置业务接口
        /// </summary>
        private readonly SysConfigService _sysService;

        public SysConfigController(IAuthenticate<TicketResponse> _manage, IHttpContextAccessor _accessor, SysConfigService sysService) : base(_manage, _accessor)
        {
            _sysService = sysService;
        }
        #endregion

        #region 获取系统配置
        /// <summary>
        /// 编辑时获取
        /// </summary>
        [AuthorizeFilter(AuthCode.SysConfig0003)]
        public JsonResult GetEdit(int configId)
        {
            //输出
            var response = new JResult<SysConfigResponse>()
            {
                Success = false
            };

            try
            {
                response.Success = true;
                response.Data = _sysService.Get(configId, _manage.data.CompanyID);
            }
            catch (Exception ex)
            {
                response.ErrorMessage = ex.Message;
            }

            return Json(response);

        }

        /// <summary>
        /// 新增时获取
        /// </summary>
        [AuthorizeFilter(AuthCode.SysConfig0002)]
        public JsonResult GetAdd(int configId)
        {
            //输出
            var response = new JResult<SysConfigResponse>()
            {
                Success = false
            };

            try
            {
                response.Success = true;
                response.Data = _sysService.Get(configId, _manage.data.CompanyID);
            }
            catch (Exception ex)
            {
                response.ErrorMessage = ex.Message;
            }

            return Json(response);
        }
        #endregion

        /// <summary>
        /// 系统配置新增或编辑
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.SysConfig0002, AuthCode.SysConfig0003)]
        public JsonResult SysConfigAddOrEdit(SysConfigAddOrEditRequest request)
        {
            var response = _sysService.AddOrEdit(request);
            return Json(response);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.SysConfig0004)]
        public JsonResult SysConfigDelete(int configId)
        {
            var response = _sysService.Delete(configId);
            return Json(response);
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<PermissionResponse></returns>
        [AuthorizeFilter(AuthCode.SysConfig0001)]
        public JsonResult GetPager(SysConfigQuery query)
        {
            query.CompanyId = _manage.data.CompanyID;

            var pager = _sysService.GetPager(query);
            return Json(pager);
        }

        #region 第三方接口信息
        /// <summary>
        /// 获取第三方接口列表
        /// </summary>
        [AuthorizeFilter(AuthCode.PaymentInterface0001)] 
        public JsonResult GetPayMentInterfaceList(PaymentInterfaceQuery query)
        {
            query.CompanyId = _manage.data.CompanyID;

            #region 权限判断
            PermissionHelper.PermissionCommon permissionModel = new PermissionHelper.PermissionCommon();
            List<string> userPermission = _manage.data.UserPermission;
            if (userPermission != null && userPermission.Count > 0)
            {
                userPermission = userPermission.Where(e => e.Contains("PaymentInterface")).ToList();
            }
 
            for (int i = 0; userPermission != null && i < userPermission.Count; i++)
            {
                //是否有——新增、修改权限
                if (userPermission[i].Equals(AuthCode.PaymentInterface0002.ToString()))
                {
                    permissionModel.CanAdd = true;
                    permissionModel.CanEdit = true;
                }
                //是否有——禁用权限
                if (userPermission[i].Equals(AuthCode.PaymentInterface0004.ToString()))
                {
                    permissionModel.CanDisable = true;
                }
                //是否有——删除权限
                if (userPermission[i].Equals(AuthCode.PaymentInterface0003.ToString()))
                {
                    permissionModel.CanDelete = true;
                }
                //是否有——查看秘钥权限
                if (userPermission[i].Equals(AuthCode.PaymentInterface0005.ToString()))
                {
                    permissionModel.CanView = true;
                }
                //是否有——查看秘钥权限
                if (userPermission[i].Equals(AuthCode.PaymentInterface0006.ToString()))
                {
                    permissionModel.BalanceView = true;
                }
            }
            query.permission = permissionModel;
            #endregion

            var response = _sysService.GetPayMentInterfaceList(query);
            return Json(response);
        }

        //检测是否有添加权限
        public JsonResult CheckAddPermission()
        {
            var response = new JResult()
            {
                Success = false
            };
            string code= AuthCode.PaymentInterface0002.ToString();
            var userPermission = _manage.data.UserPermission.Where(e => e.Equals(code)).FirstOrDefault();
            if (userPermission != null)
            {
                response.Success = true;
                response.SuccessMessage = code;
            }
            return Json(response);
        }

        /// <summary>
        /// 获取某第三方接口详细信息
        /// </summary>
        public JsonResult GetDetail(PaymentInterfaceQuery query)
        {
            //int companyID = query.CompanyId.Value;
            var data = _sysService.GetDetail(query);
            return Json(data);
        }

        /// <summary>
        /// 获取某第三方接口多重信息
        /// </summary>
        public JsonResult GetManyInfo(PaymentInterfaceQuery query)
        {
            if (query.CompanyId == null)
            {
                query.CompanyId = _manage.data.CompanyID;
            }
            query.permission = GetPermissionModel();
            var data = _sysService.GetManyInfo(query);
            return Json(data);
        }

        public PermissionCommon GetPermissionModel()
        {
            PermissionCommon permissionModel = new PermissionCommon();
            var item = _manage.data.UserPermission.Where(e => e == AuthCode.PaymentInterface0005.ToString()).FirstOrDefault();
            if (item != null)
            {
                permissionModel.CanView = true;
            }
            return permissionModel;
        }
        /// <summary>
        /// 付款接口新增或编辑
        /// </summary>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.PaymentInterface0002)]
        public JsonResult PaymentInterfaceAddOrEdit(PaymentInterfaceAddOrEditRequest request)
        {
            return null;
        }

        //添加或修改
        [AuthorizeFilter(AuthCode.PaymentInterface0002)]
        public JsonResult AddOrEditInterface(PaymentInterfaceQuery query)
        {
            query.permission = GetPermissionModel();
            query.UserName = _manage.data.UserName;
            if (!ModelState.IsValid)
            {
                var message = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage).FirstOrDefault();
                return Json(new JResult()
                {
                    Success = false,
                    ErrorMessage = message
                });
            }
            if (query.permission.CanView)
            {
                if (string.IsNullOrEmpty(query.SecretKey))
                {
                    return Json(new JResult()
                    {
                        Success = false,
                        ErrorMessage = "秘钥不能为空"
                    });
                }
                if (query.SecretKey.Length>64)
                {
                    return Json(new JResult()
                    {
                        Success = false,
                        ErrorMessage = "秘钥长度超出"
                    });
                }
            }

            if (query.LimitCloseDate!=null)
            {
                query.LimitCloseDate = DateTime.Now.ToString("yyyy-MM-dd ")+ query.LimitCloseDate+":00:00";
            }
            if (query.LimitOpenDate!=null)
            {
                query.LimitOpenDate = DateTime.Now.ToString("yyyy-MM-dd ") + query.LimitOpenDate + ":00:00";
            }
            var data = _sysService.AddOrEditInterface(query);
            return Json(data);
        }

        //修改状态
        [AuthorizeFilter(AuthCode.PaymentInterface0004)]
        public JsonResult UpdateStatus(PaymentInterfaceQuery query)
        {
            var data = _sysService.UpdateStatus(query);
            return Json(data);
        }

        //删除
        [AuthorizeFilter(AuthCode.PaymentInterface0003)]
        public JsonResult DeleteInterface(PaymentInterfaceQuery query)
        {
            var data = _sysService.DeleteInterface(query);
            return Json(data);
        }

        // 获取交易类型列表
        public JsonResult GetTypeList(SysConfigAddOrEditRequest sysRequest)
        {
            sysRequest.ConfigCode = "PaymentInterface";
            //sysRequest.CompanyId = _manage.data.CompanyID;
            var response = _sysService.GetTransTypeList(sysRequest);
            return Json(response);
        }

        // 获取交易类型列表
        public JsonResult GetPaymentTypeList(SysConfigAddOrEditRequest sysRequest)
        {
            var response = _sysService.GetTransTypeListNew(sysRequest);
            return Json(response);
        }
        #endregion

        /// <summary>
        /// 获取推送地址列表
        /// </summary>
        //[AuthorizeFilter(AuthCode.PushAddressList0001)]
        //public JsonResult GetPushAddressList([FromBody]PushAddressQuery query)
        //{
        //    query.CompanyId = _manage.data.CompanyID;
        //    var response = _sysService.GetPushAddressList(query);
        //    return Json(response);
        //}

        public JsonResult CommonGetKey()
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                string data = EncryptHelper.enSHA256(Guid.NewGuid().ToString("N"));
                string appkey = data.Substring(0, 32);
                string secret = string.Empty;
                string secretKey = string.Empty;

                if (string.IsNullOrEmpty(appkey))
                {
                    response.ErrorMessage = "获取appkey出错";
                    return Json(response);
                }
                else
                {
                    System.Threading.Thread.Sleep(1000);
                    secret = EncryptHelper.enSHA256(Guid.NewGuid().ToString("N"));
                    secretKey = secret.Substring(0, 64);
                }
                if (string.IsNullOrEmpty(secretKey))
                {
                    response.ErrorMessage = "获取secretKey出错";
                    return Json(response);
                }

                response.StatusCode = appkey;
                response.SuccessMessage = secretKey;
            }
            catch (Exception)
            {
                response.ErrorMessage = "服务器异常";
                return Json(response);
            }
            response.Success = true;
            return Json(response);
        }

        //生成存款key和SecretKey
        [AuthorizeFilter(AuthCode.GetExtApi003)] 
        public JsonResult GetNewKeyByDeposit()
        {
            return CommonGetKey();
        }

        //生成付款key和SecretKey
        [AuthorizeFilter(AuthCode.GetExtApi004)]
        public JsonResult GetNewKeyByPayment()
        {
            return CommonGetKey();
        }

        //生成中转key和SecretKey
        [AuthorizeFilter(AuthCode.GetExtApi006)]
        public JsonResult GetNewKeyByTransfer()
        {
            return CommonGetKey();
        }

    }
}